import axios from "axios";
import { Toast } from 'vant';

const configOptions = {
  baseURL: 'https://api.github.com/',
  timeout: 3000,
  // headers: { 'X-Custom-Header': 'foobar' }
}

const instance = axios.create(configOptions)

instance.interceptors.request.use(config => {
  console.log(`==== ${config.url} ==== 入参：：`, config)
  return config
})

instance.interceptors.response.use(res => {
  console.log(`==== ${res.config.url} ==== 出参：：`, res)
  return res
})

const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      url,
      data,
      method: 'post',
      ...config
    }).then(res => {
      resolve(res)
    }).catch(err => {
      console.error(`接口 ${err.config.url} 报错：`, err.message)
      console.error(`具体报错原因：`, err)
      Toast(`接口 ${err.config.url} 报错`);
      reject(err)
    })
  })
}

const get = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      url,
      params,
      method: 'get',
      ...config
    }).then(res => {
      resolve(res)
    }).catch(err => {
      console.error(`接口 ${err.config.url} 报错：`, err.message)
      console.error(`具体报错原因：`, err)
      Toast(`接口 ${err.config.url} 报错`);
      reject(err)
    })
  })
}

export {
  post, get
}
